package edu.ntu.cloudroid.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.log.AppLogLine;
import com.google.appengine.api.log.LogQuery;
import com.google.appengine.api.log.LogServiceFactory;
import com.google.appengine.api.log.LogService.LogLevel;
import com.google.appengine.api.log.RequestLogs;

public class GetLogs extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final int limit = 200;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String offset = req.getParameter("offset");
		
		PrintWriter pw = resp.getWriter();
		LogQuery query = LogQuery.Builder.withDefaults();
		query.includeAppLogs(true);
		query.minLogLevel(LogLevel.INFO);
		
		if (null != offset)
			query.offset(offset);
		
		String lastOffset = null;
		int i = 0;
		
		for (RequestLogs record : LogServiceFactory.getLogService().fetch(query)) {
			lastOffset = record.getOffset();
			
			for (AppLogLine appLog : record.getAppLogLines()) {
				pw.println(appLog.getLogMessage());
			}
			
			if (++i > limit)
				break;
		}
		
		if (null!= lastOffset)
			pw.printf("OFFSET=%s\n", lastOffset);
	}
}
